# coding=utf-8
from sqlalchemy import func

from database.models.ControllerType import ControllerType
from database.models.ControllerType import Session, Base, engine
from database.models.MasterInfo import MasterInfo
from database.models.OptType import OptType
from database.models.UserInfo import UserInfo


def InitDatabase():
    Base.metadata.create_all(engine)

    # Insert Controller Type

    session = Session()
    TypeCount = session.query(func.count('*')).select_from(ControllerType).scalar()
    if TypeCount is 0:
        ctrolertype = ControllerType(desc='BinaryController')
        session.add(ctrolertype)
        ctrolertype = ControllerType(desc='GradeController')
        session.add(ctrolertype)
        ctrolertype = ControllerType(desc='KeyPanel')
        session.add(ctrolertype)
        session.commit()

    # insert opt type
    OptCount = session.query(func.count('*')).select_from(OptType).scalar()
    if OptCount is 0:
        opt = OptType(desc='Open Binary Key')
        session.add(opt)
        opt = OptType(desc='Close Binary Key')
        session.add(opt)
        opt = OptType(desc='Delay ms Params for ms default 200')
        session.add(opt)
        opt = OptType(desc='Run a Normal Flow')
        session.add(opt)
        opt = OptType(desc=u'根据id停止指定模式,参数是模式id')
        session.add(opt)
        session.commit()
    # insert master info
    infoCount = session.query(func.count('*')).select_from(MasterInfo).scalar()
    if infoCount is 0:
        info = MasterInfo(name='longitude', value='116.31')
        session.add(info)
        info = MasterInfo(name='latitude', value='39.91')
        session.add(info)
        session.commit()

    # insert user info
    infoCount = session.query(func.count('*')).select_from(UserInfo).scalar()
    if infoCount is 0:
        info = UserInfo(Name='hanlaoban', Passwd='niuX')
        session.add(info)
        session.commit()
